package com.ruicar.afs.cloud.apply.pre.loan.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.apply.business.service.ApplySequenceService;
import com.ruicar.afs.cloud.apply.business.service.TSysParamConfigService;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.contract.service.ApplyContractInfoService;
import com.ruicar.afs.cloud.apply.pre.approve.service.PreApproveService;
import com.ruicar.afs.cloud.apply.pre.loan.condition.*;
import com.ruicar.afs.cloud.apply.pre.loan.mapper.ApplyReportMapper;
import com.ruicar.afs.cloud.apply.pre.loan.service.*;
import com.ruicar.afs.cloud.apply.pre.loan.vo.ApplyReportVO;
import com.ruicar.afs.cloud.apply.pre.loan.vo.AssetChangeVo;
import com.ruicar.afs.cloud.apply.pre.loan.vo.AssetContentVO;
import com.ruicar.afs.cloud.apply.pre.loan.vo.OrderMngVO;
import com.ruicar.afs.cloud.bizcommon.business.bean.FinanceCalculatorBean;
import com.ruicar.afs.cloud.bizcommon.business.bean.FinanceInfoBean;
import com.ruicar.afs.cloud.bizcommon.business.dto.CalculatorDTO;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinDiscountDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinFinancingItems;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinRentAdjustDetails;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyDiscountDetailsService;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyFinancingItemsService;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyRentAdjustDetailsService;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.security.vo.RoleVo;
import com.ruicar.afs.cloud.common.core.uid.UidGenerator;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.CaseCarStyleDetailDto;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysVehicleDetail;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysVehicleModel;
import com.ruicar.afs.cloud.parameter.commom.enums.CarNature;
import com.ruicar.afs.cloud.parameter.commom.enums.CostType;
import com.ruicar.afs.cloud.parameter.commom.enums.OrderOprType;
import com.ruicar.afs.cloud.parameter.commom.enums.WhetherEnum;
import com.ruicar.afs.cloud.parameter.commom.service.TsysVehicleDetailService;
import com.ruicar.afs.cloud.parameter.commom.service.TsysVehicleModelService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description: 申请提报
 * @author: sijun.yu
 * @date: 2020/5/12 13:22
 */
@Slf4j
@Service
@AllArgsConstructor
public class ApplyReportServiceImpl extends ServiceImpl<ApplyReportMapper, ApplyBusinessConfig> implements ApplyReportService {

    private final ApplyFinancingItemsService applyFinancingItemsService;
    private final ApplyRentAdjustDetailsService applyRentAdjustDetailsService;
    private final ApplyCostDetailsService applyCostDetailsService;
    private final ApplyContractInfoService applyContractInfoService;
    private final ApplyDiscountDetailsService applyDiscountDetailsService;
    private final ApplyCarDetailsService applyCarDetailsService;
    private ApplyOrderInfoService orderInfoService;
    private ApplyCarDetailsService carDetailsService;
    private ApplyChannelInfoService channelInfoService;
    private ApplyAffiliatedUnitService affiliatedUnitService;
    private ApplyCustBaseInfoService custBaseInfoService;
    private ApplyCustPersonalService custPersonalService;
    private ApplyCustContactsService custContactsService;
    private ApplyCustAddressService custAddressService;
    private ApplyCostDetailsService costDetailsService;
    private ApplyDiscountDetailsService discountDetailsService;
    private ApplyFinancingItemsService financingItemsService;
    private ApplyRentAdjustDetailsService rentAdjustDetailsService;
    private ApplyProductService productService;
    private final TsysVehicleDetailService tsysVehicleDetailService;
    private final TsysVehicleModelService tsysVehicleModelService;
    private final ApplyModifyHistoryService applyModifyHistoryService;
    private final ApplyOprRecordService applyOprRecordService;
    private PreApproveService preApproveService;
    private ApplySequenceService applySequenceService;
    private final TSysParamConfigService tSysParamConfigService;
    private UidGenerator uidGenerator;

    /**
     * 查询贷款信息【汇总】
     *
     * @param vo
     * @param condition
     * @return
     */
    public FinanceCalculatorBean getFinanceCostAll(FinanceCalculatorBean vo, CalculatorDTO condition) {

        vo = new FinanceCalculatorBean();
        String applyNo = condition.getApplyNo();
        // 合计信息
        costDetailsService.getFinanceCostTotal(vo, condition);
        // 附加产品
        String isAdditional = WhetherEnum.No.getIndex();
        FinanceInfoBean addProductInfo = costDetailsService.getAddProductInfo(applyNo, condition.getCarId(), ApplyConstants.COST_TYPE_ADD_LOAN);
        if (addProductInfo != null) {
            isAdditional = WhetherEnum.YES.getIndex();
            vo.setAddProductInfo(addProductInfo);
            vo.setIsAdditional(isAdditional);
        }
        // 初始化-车辆价格
        ApplyReportVO reportVO = this.initProductParam(applyNo);
        Assert.isTrue(reportVO != null, "请检查资产信息车辆价格是否保存");
        vo.setSalePrice(reportVO.getSalePrice());
        // 车辆产品
        FinanceInfoBean carProductInfo = costDetailsService.getCarProductInfo(applyNo, condition.getCarId(), ApplyConstants.COST_TYPE_CAR_LOAN);
        // 是否有子产品
        if (carProductInfo != null) {
            FinCostDetails costInfo = carProductInfo.getCostInfo();
            String isSubProduct = costInfo.getIsSubProduct();
            if (WhetherEnum.No.getIndex().equals(isSubProduct)) {
                isAdditional = WhetherEnum.YES.getIndex();
            }
            vo.setIsSubProduct(isSubProduct);
            costInfo.setContractAmt(reportVO.getSalePrice());// 车辆价格
            carProductInfo.setCostInfo(costInfo);
            vo.setCarProductInfo(carProductInfo);
            vo.setIsAdditional(isAdditional);
        }
        // 租金调整
        List<FinRentAdjustDetails> rentList = rentAdjustDetailsService.getRentAdjustDetails(condition.getApplyNo());
        if (rentList != null && rentList.size() > 0) {
            vo.setRentList(rentList);
        }

        return vo;
    }

    /**
     * 业务类型下拉列表
     *
     * @param condition
     * @return
     */
    @Override
    public List<ApplyBusinessConfig> getBusinessOptionList(ApplyReportCondition condition) {
        return this.baseMapper.getBusinessOption(condition);
    }

    /**
     * 留言列表
     *
     * @param condition
     * @return
     */
    @Override
    public List<ApplyRemindDetails> getRemindDetailsList(RemindDetailsCondition condition) {
        return this.baseMapper.getRemindDetailsList(condition);
    }

    /**
     * 进件申请-订单管理
     *
     * @param page
     * @param condition
     * @return
     */
    @Override
    public IPage<OrderMngVO> getLoanApplyList(Page page, ApplyReportCondition condition) {
        // 用户名
        condition.setCreateBy(SecurityUtils.getUsername());
        JSONArray jsonArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray("deptIds");
        if (jsonArray != null) {
            // 部门列表
            condition.setDeptIds(jsonArray.toJavaList(String.class));
        }
        JSONArray roleArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray("roles");
        if (roleArray != null) {
            List<RoleVo> roleList = roleArray.toJavaList(RoleVo.class);
            condition.setRoleList(roleList);
        }
        return this.baseMapper.getLoanApplyList(page, condition);
    }

    /**
     * 订单操作记录表
     *
     * @param page
     * @param condition
     * @return
     */
    @Override
    public IPage<OrderMngVO> getOrderOprList(Page page, OrderOprCondition condition) {
        return this.baseMapper.getOrderOprList(page, condition);
    }

    /**
     * 查询产品列表，传入参数的数据
     *
     * @param applyNO
     * @return
     */
    @Override
    public ApplyReportVO initProductParam(String applyNO) {

        ApplyReportVO applyReportVO = this.baseMapper.initProductParam(applyNO);
        return applyReportVO;
    }

    /**
     * 复制订单功能
     *
     * @param oldApplyNo
     * @return
     */
    @Override
    public String saveCopyOrderInfo(String oldApplyNo) {

        String userName = SecurityUtils.getUsername();
        ApplyOrderInfo orderInfo = orderInfoService.getOrderInfoByApplyNo(oldApplyNo);
        if (orderInfo != null) {
            String applyNo = applySequenceService.getTempNoForApply();
            // 复制订单信息
            ApplyOrderInfo applyOrderInfo = new ApplyOrderInfo();
            BeanUtils.copyProperties(orderInfo, applyOrderInfo);
            applyOrderInfo.setId(null);
            applyOrderInfo.setApplyNo(applyNo);
            applyOrderInfo.setApplyStatus(ApplyConstants.APPLY_STATUS_DRAFT);
            applyOrderInfo.setCreateTime(new Date());
            applyOrderInfo.setCreateBy(userName);
            applyOrderInfo.setApplyReporter(null);//提报单员
            applyOrderInfo.setRiskPassDate(null);// 核准日期
            applyOrderInfo.setCancelDate(null);// 取消日期
            applyOrderInfo.setIntoFirstDate(null);// 首次提交日期
            orderInfoService.save(applyOrderInfo);
            // 复制渠道信息
            ApplyChannelInfo channelInfo = channelInfoService.getChannelInfoByApplyNo(oldApplyNo);
            if (channelInfo != null) {
                ApplyChannelInfo applyChannelInfo = new ApplyChannelInfo();
                BeanUtils.copyProperties(channelInfo, applyChannelInfo);
                applyChannelInfo.setId(null);
                applyChannelInfo.setApplyNo(applyNo);
                applyChannelInfo.setCreateTime(new Date());
                applyChannelInfo.setCreateBy(userName);
                channelInfoService.save(applyChannelInfo);
            }
            // 复制资产信息
            ApplyCarDetails carDetails = carDetailsService.getCarDetailsByApplyNo(oldApplyNo);
            if (carDetails != null) {
                ApplyCarDetails applyCarDetails = new ApplyCarDetails();
                BeanUtils.copyProperties(carDetails, applyCarDetails);
                applyCarDetails.setId(null);
                applyCarDetails.setApplyNo(applyNo);
                applyCarDetails.setCreateTime(new Date());
                applyCarDetails.setCreateBy(userName);
                if (CarNature.NEW_CAR.getIndex().equals(applyOrderInfo.getCarNature())) {
                    applyCarDetails.setCarVin(null);// 新车VIN置空
                    applyCarDetails.setFullModelNum(null);// 车辆型号
                    applyCarDetails.setEngineNo(null);// 发动机号
                }
                applyCarDetails.setContractNo(null);// 合同编号
                carDetailsService.save(applyCarDetails);

                // 复制费用信息
                List<FinCostDetails> costList = costDetailsService.getCostDetailsList(oldApplyNo);
                if (costList != null && costList.size() > 0) {
                    for (FinCostDetails costDetails : costList) {
                        FinCostDetails finCostDetails = new FinCostDetails();
                        BeanUtils.copyProperties(costDetails, finCostDetails);
                        finCostDetails.setId(uidGenerator.getUID());
                        finCostDetails.setCarId(applyCarDetails.getId());
                        finCostDetails.setApplyNo(applyNo);
                        finCostDetails.setCreateTime(new Date());
                        finCostDetails.setCreateBy(userName);
                        costDetailsService.save(finCostDetails);
                        // 复制贴息列表
                        List<FinDiscountDetails> discountList = discountDetailsService.getDiscountDetailsList(oldApplyNo, costDetails.getId());
                        if (discountList != null && discountList.size() > 0) {
                            for (FinDiscountDetails discountDetails : discountList) {
                                FinDiscountDetails finDiscountDetails = new FinDiscountDetails();
                                BeanUtils.copyProperties(discountDetails, finDiscountDetails);
                                finDiscountDetails.setId(uidGenerator.getUID());
                                finDiscountDetails.setApplyNo(applyNo);
                                finDiscountDetails.setCostId(finCostDetails.getId());
                                finDiscountDetails.setCreateTime(new Date());
                                finDiscountDetails.setCreateBy(userName);
                                discountDetailsService.save(finDiscountDetails);
                            }
                        }
                    }
                    // 复制融资列表
                    List<FinFinancingItems> itmeList = financingItemsService.getFinancingItemsList(oldApplyNo, carDetails.getId());
                    if (itmeList != null && itmeList.size() > 0) {
                        for (FinFinancingItems financingItems : itmeList) {
                            FinFinancingItems finFinancingItems = new FinFinancingItems();
                            BeanUtils.copyProperties(financingItems, finFinancingItems);
                            finFinancingItems.setId(uidGenerator.getUID());
                            finFinancingItems.setApplyNo(applyNo);
                            finFinancingItems.setCarId(applyCarDetails.getId());
                            finFinancingItems.setCreateTime(new Date());
                            finFinancingItems.setCreateBy(userName);
                            financingItemsService.save(finFinancingItems);
                            // 子融资项目
                            List<FinFinancingItems> sonList = financingItemsService.getApplyFinancingItemsList(oldApplyNo, financingItems.getId());
                            if (sonList != null && sonList.size() > 0) {
                                for (FinFinancingItems sonItems : sonList) {
                                    FinFinancingItems items = new FinFinancingItems();
                                    BeanUtils.copyProperties(sonItems, items);
                                    items.setId(uidGenerator.getUID());
                                    items.setApplyNo(applyNo);
                                    items.setCarId(applyCarDetails.getId());
                                    items.setUpperId(finFinancingItems.getId());
                                    items.setCreateTime(new Date());
                                    items.setCreateBy(userName);
                                    financingItemsService.save(items);
                                }
                            }
                        }
                    }
                    // 赋值租金调整
                    List<FinRentAdjustDetails> rentList = rentAdjustDetailsService.getRentAdjustDetails(oldApplyNo);
                    if (rentList != null && rentList.size() > 0) {
                        for (FinRentAdjustDetails rentAdjustDetails : rentList) {
                            FinRentAdjustDetails finRentAdjustDetails = new FinRentAdjustDetails();
                            BeanUtils.copyProperties(rentAdjustDetails, finRentAdjustDetails);
                            finRentAdjustDetails.setId(uidGenerator.getUID());
                            finRentAdjustDetails.setApplyNo(applyNo);
                            finRentAdjustDetails.setCreateTime(new Date());
                            finRentAdjustDetails.setCreateBy(userName);
                            rentAdjustDetailsService.save(finRentAdjustDetails);
                        }
                    }
                }
            }
            // 复制挂靠信息
            ApplyAffiliatedUnit affiliatedUnit = affiliatedUnitService.getAffiliatedUnitByApplyNo(oldApplyNo);
            if (affiliatedUnit != null) {
                ApplyAffiliatedUnit applyAffiliatedUnit = new ApplyAffiliatedUnit();
                BeanUtils.copyProperties(affiliatedUnit, applyAffiliatedUnit);
                applyAffiliatedUnit.setId(null);
                applyAffiliatedUnit.setApplyNo(applyNo);
                applyAffiliatedUnit.setCreateTime(new Date());
                applyAffiliatedUnit.setCreateBy(userName);
                applyAffiliatedUnit.setModifyFlag(null);
                affiliatedUnitService.save(applyAffiliatedUnit);
            }
            // 复制客户信息
            List<ApplyCustBaseInfo> custList = custBaseInfoService.getCustBaseInfoList(oldApplyNo);
            if (custList != null && custList.size() > 0) {
                for (ApplyCustBaseInfo custBaseInfo : custList) {
                    ApplyCustBaseInfo applyCustBaseInfo = new ApplyCustBaseInfo();
                    BeanUtils.copyProperties(custBaseInfo, applyCustBaseInfo);
                    applyCustBaseInfo.setId(null);
                    applyCustBaseInfo.setApplyNo(applyNo);
                    applyCustBaseInfo.setCreateTime(new Date());
                    applyCustBaseInfo.setCreateBy(userName);
                    applyCustBaseInfo.setIsLock(null);
                    applyCustBaseInfo.setRiskQueriedFlag(null);
                    custBaseInfoService.save(applyCustBaseInfo);
                    // 复制客户明细
                    ApplyCustPersonalDetail custPersonalDetail = custPersonalService.getCustPersonalDetail(oldApplyNo, custBaseInfo.getId());
                    if (custPersonalDetail != null) {
                        ApplyCustPersonalDetail applyCustPersonalDetail = new ApplyCustPersonalDetail();
                        BeanUtils.copyProperties(custPersonalDetail, applyCustPersonalDetail);
                        applyCustPersonalDetail.setId(null);
                        applyCustPersonalDetail.setApplyNo(applyNo);
                        applyCustPersonalDetail.setCustId(applyCustBaseInfo.getId());
                        applyCustPersonalDetail.setCreateTime(new Date());
                        applyCustPersonalDetail.setCreateBy(userName);
                        custPersonalService.save(applyCustPersonalDetail);
                    }
                    // 复制地址列表
                    List<ApplyCustAddressDetails> addressDetailsList = custAddressService.getCustAddressDetailsList(oldApplyNo, custBaseInfo.getId());
                    if (addressDetailsList != null && addressDetailsList.size() > 0) {
                        for (ApplyCustAddressDetails custAddressDetails : addressDetailsList) {
                            ApplyCustAddressDetails applyCustAddressDetails = new ApplyCustAddressDetails();
                            BeanUtils.copyProperties(custAddressDetails, applyCustAddressDetails);
                            applyCustAddressDetails.setId(null);
                            applyCustAddressDetails.setApplyNo(applyNo);
                            applyCustAddressDetails.setCustId(applyCustBaseInfo.getId());
                            applyCustAddressDetails.setCreateTime(new Date());
                            applyCustAddressDetails.setCreateBy(userName);
                            custAddressService.save(applyCustAddressDetails);
                        }
                    }
                }
                // 复制联系人列表
                List<ApplyCustContacts> contactsList = custContactsService.getCustContactsList(oldApplyNo);
                if (contactsList != null && contactsList.size() > 0) {
                    for (ApplyCustContacts custContacts : contactsList) {
                        ApplyCustContacts applyCustContacts = new ApplyCustContacts();
                        BeanUtils.copyProperties(custContacts, applyCustContacts);
                        applyCustContacts.setId(null);
                        applyCustContacts.setApplyNo(applyNo);
                        applyCustContacts.setCreateTime(new Date());
                        applyCustContacts.setCreateBy(userName);
                        applyCustContacts.setIsLock(null);
                        custContactsService.save(applyCustContacts);
                    }
                }
            }
            return applyNo;
        }
        return null;
    }


    /**
     * 保存和更新车辆信息
     *
     * @param applyNo
     * @param condition
     * @return
     */
    @Override
    public ApplyCarDetails saveOrUpdateCarInfo(String applyNo, CarInfoCondition condition) {

        ApplyCarDetails carDetails = carDetailsService.getCarDetailsByApplyNo(applyNo);
        if (carDetails != null) {
            productService.updateFinanceInfoForSalePrice(applyNo, carDetails, condition);
            carDetailsService.updateCarInfo(carDetails, condition);
        } else {
            carDetails = carDetailsService.saveCarInfo(applyNo, condition);
        }
        return carDetails;
    }

    /**
     * 保存资产变更前的需要展示的数据-数据留痕
     * 保存资产变更操作记录
     *
     * @param condition
     */
    @Override
    public IResponse saveAssertData(AllOrderCondition condition) {
        //权限判断
        ApplyOrderInfo orderInfoByApplyNo = orderInfoService.getOrderInfoByApplyNo(condition.getApplyNo());
        BigDecimal addAmt = BigDecimal.ZERO;
        String username = SecurityUtils.getUsername();
        if (!orderInfoByApplyNo.getCreateBy().equals(username)) {
            return IResponse.fail("无权限查看").setCode("0005");
        }
        //查询合同信息
        ApplyContractInfo contractInfoByAppplyNo = this.applyContractInfoService.getContractInfoByAppplyNo(condition.getApplyNo());
        //融资信息
        List<FinCostDetails> costDetailsList = this.applyCostDetailsService.getCostDetailsList(condition.getApplyNo());
        if (ObjectUtil.isNotNull(contractInfoByAppplyNo)) {
            if (contractInfoByAppplyNo.getStartDate() != null) {
                return IResponse.fail("该订单已经放款，无法进行资产变更").setCode("0002");
            } else if (ApplyConstants.CONTRACT_STATUS_CANCEL.equals(contractInfoByAppplyNo.getContractStatus())) {
                //合同取消的不可进行资产变更
                return IResponse.fail("该订单已合同取消，无法进行资产变更").setCode("0006");
            } else if (ApplyConstants.CONTRACT_STATUS_APPROVE.equals(contractInfoByAppplyNo.getContractStatus())) {
                //合同取消的不可进行资产变更
                return IResponse.fail("该订单放款审核中，无法进行资产变更").setCode("0007");
            }
        }
        //核准的订单超过20天，不可做资产变更
        int day = Integer.parseInt(tSysParamConfigService.getParamValue("preLoanAssertChange", "day", "20"));
        //判斷核准時間是否已超過20天
        int compare = new Date().compareTo(orderInfoByApplyNo.getRiskPassDate());
        if (compare > day) {
            //判断核准时间至当前时间是否已过期
            return IResponse.fail("资产变更核准已超过" + day + "天,不允许发起资产变更").setCode("0003");
        }
        //初次提交资产变更
        AssetChangeVo assetChangeVo = new AssetChangeVo();
        AssetContentVO historyContent = new AssetContentVO();
        //查询资产变更操作记录
        List<ApplyOprRecord> applyOprRecordList = this.applyOprRecordService.list(Wrappers.<ApplyOprRecord>query().lambda()
                .eq(ApplyOprRecord::getApplyNo, condition.getApplyNo())
                .eq(ApplyOprRecord::getApplyType, OrderOprType.ASSERTCHANGE));
        if (CollectionUtil.isNotEmpty(applyOprRecordList)) {
            //获取资产变更次数(count) String paramNo,String magicNo,String defaultValue
            int count = Integer.parseInt(tSysParamConfigService.getParamValue("preLoanAssertChange", "number", "2"));
            if (applyOprRecordList.size() >= count) {
                return IResponse.fail("资产变更次数用尽").setCode("0001");
            }
            for (ApplyOprRecord applyOprRecord : applyOprRecordList) {
                //判断审批时间
                if (applyOprRecord.getApproveDate() == null) {
                    return IResponse.fail("资产变更请求审批中,不允许发起资产变更").setCode("0004");
                }
            }

        }
        //查询车辆信息
        BigDecimal totalContractAmt = BigDecimal.ZERO;
        BigDecimal hundred = new BigDecimal("100");
        if (CollectionUtil.isNotEmpty(costDetailsList)) {
            for (FinCostDetails finCostDetails : costDetailsList) {
                if (CostType.CARAMT.getIndex().equals(finCostDetails.getCostType())) {
                    assetChangeVo.setLoanAmt(finCostDetails.getLoanAmt());
                    assetChangeVo.setLoanTerm(finCostDetails.getLoanTerm());
                    assetChangeVo.setDownPayScale(finCostDetails.getDownPayScale());
                    totalContractAmt = totalContractAmt.add(finCostDetails.getContractAmt());
                    if (WhetherEnum.No.getIndex().equals(finCostDetails.getIsSubProduct())) {
                        addAmt = finCostDetails.getAddAmt();
                        assetChangeVo.setAddAmt(finCostDetails.getAddAmt().multiply(hundred.subtract(finCostDetails.getDownPayScale())).divide(hundred, 2, BigDecimal.ROUND_HALF_DOWN));
                        totalContractAmt = totalContractAmt.add(addAmt);
                    }
                    assetChangeVo.setSalePrice(finCostDetails.getContractAmt());
                    assetChangeVo.setFinanceItemName(finCostDetails.getProductName());
                } else if (CostType.AFFIXAMT.getIndex().equals(finCostDetails.getCostType())) {
                    assetChangeVo.setAddAmt(finCostDetails.getLoanAmt());
                    assetChangeVo.setAddLoanTerm(finCostDetails.getLoanTerm());
                    assetChangeVo.setAddDownPayScale(finCostDetails.getDownPayScale());
                    addAmt = finCostDetails.getContractAmt();
                    totalContractAmt = totalContractAmt.add(finCostDetails.getContractAmt());
                }
            }
            historyContent.setFinCostDetailsList(costDetailsList);
        }
        assetChangeVo.setContractAmt(totalContractAmt);
        // 租金调整
        List<FinRentAdjustDetails> rentAdjustDetails = this.applyRentAdjustDetailsService.getRentAdjustDetails(condition.getApplyNo());
        historyContent.setFinRentAdjustDetailsList(rentAdjustDetails);
        // 融资项
        List<FinFinancingItems> applyFinancingItemsList = this.applyFinancingItemsService.getFinancingItemsList(condition.getApplyNo(), null);
        if (CollectionUtil.isNotEmpty(applyFinancingItemsList)) {
            historyContent.setFinFinancingItemsList(applyFinancingItemsList);
            StringBuilder sb = new StringBuilder("总额:" + addAmt + ",");
            for (int i = 0; i < applyFinancingItemsList.size(); i++) {
                List<FinFinancingItems> sonList = financingItemsService.getApplyFinancingItemsList(condition.getApplyNo(), applyFinancingItemsList.get(i).getId());
                if (StringUtil.isNotEmpty(applyFinancingItemsList.get(i).getFinanceItemName())) {
                    sb.append(applyFinancingItemsList.get(i).getFinanceItemName()).append("(").append(applyFinancingItemsList.get(i).getFinanceItemAmt()).append(")");
                    if (i < applyFinancingItemsList.size() - 1) {
                        if (sonList != null && sonList.size() > 0){
                            sb.append(":");
                        }else{
                            sb.append(",");
                        }
                    }
                }
                if (sonList != null && sonList.size() > 0) {
                    for (int j = 0; j < sonList.size(); j++) {
                        sb.append(sonList.get(j).getFinanceItemName()).append("(").append(sonList.get(j).getFinanceItemAmt().setScale(2)).append(")");
                        if (j < sonList.size() - 1) {
                            sb.append("+");
                        }
                    }
                    if (i < applyFinancingItemsList.size() - 1) {
                        sb.append(",");
                    }
                }
            }
            //附加贷名
            assetChangeVo.setAddLoanName(sb.toString());
        }
        //贴息
        List<FinDiscountDetails> finDiscountDetailsList = this.applyDiscountDetailsService
                .list(Wrappers.<FinDiscountDetails>query().lambda().eq(FinDiscountDetails::getApplyNo, condition.getApplyNo()));
        if (CollectionUtil.isNotEmpty(finDiscountDetailsList)) {
            historyContent.setFinDiscountDetailsList(finDiscountDetailsList);
        }
        //车辆信息
        List<ApplyCarDetails> carDetailsList = this.applyCarDetailsService.list(Wrappers.<ApplyCarDetails>query()
                .lambda().eq(ApplyCarDetails::getApplyNo, condition.getApplyNo()));
        if (CollectionUtil.isNotEmpty(carDetailsList)) {
            ArrayList<CaseCarStyleDetailDto> caseCarStyleDetailList = new ArrayList<>();
            for (ApplyCarDetails applyCarDetails : carDetailsList) {
                assetChangeVo.setModelName(applyCarDetails.getModelName());
                assetChangeVo.setBrandName(applyCarDetails.getBrandName());
                assetChangeVo.setStyleName(applyCarDetails.getStyleName());
                //查询款式信息
                TsysVehicleDetail vehicleDetail = this.tsysVehicleDetailService.getOne(Wrappers.<TsysVehicleDetail>query().lambda()
                        .eq(TsysVehicleDetail::getModelCode, applyCarDetails.getModelId()).eq(TsysVehicleDetail::getName, applyCarDetails.getStyleName()));
                //查询车型信息
                TsysVehicleModel tsysVehicleModel = this.tsysVehicleModelService.getOne(Wrappers.<TsysVehicleModel>query().lambda()
                        .eq(TsysVehicleModel::getBrandCode, applyCarDetails.getBrandId()).eq(TsysVehicleModel::getFullName, applyCarDetails.getModelName()));
                CaseCarStyleDetailDto caseCarStyleDetailDTO = new CaseCarStyleDetailDto();
                if (ObjectUtil.isNotNull(applyCarDetails)) {
                    caseCarStyleDetailDTO.setCarId(applyCarDetails.getId());
                    caseCarStyleDetailDTO.setDisplacement(applyCarDetails.getCarDisplacement());
                    caseCarStyleDetailDTO.setFuelType(applyCarDetails.getFuelType());
                    caseCarStyleDetailDTO.setPassengers(applyCarDetails.getTotalPassenger());
                }
                if (ObjectUtil.isNotNull(vehicleDetail)) {
                    caseCarStyleDetailDTO.setCarLength(vehicleDetail.getCarLength());
                    caseCarStyleDetailDTO.setEmissionStandard(vehicleDetail.getBlowoff());
                    caseCarStyleDetailDTO.setTotalQuality(vehicleDetail.getWight());
                    caseCarStyleDetailDTO.setIsGreen(vehicleDetail.getIsGreen());
                    caseCarStyleDetailDTO.setCarType(vehicleDetail.getCarType());
                    caseCarStyleDetailDTO.setCarTypeDetail(vehicleDetail.getCarTypeDetail());
                }
                if (ObjectUtil.isNotNull(tsysVehicleModel)) {
                    caseCarStyleDetailDTO.setType(tsysVehicleModel.getType());
                }
                caseCarStyleDetailList.add(caseCarStyleDetailDTO);
            }
            historyContent.setFinCarStyleDetailList(caseCarStyleDetailList);
            historyContent.setFinCarDetailsList(carDetailsList);
        }
        //数据留痕beforeChange
        ApplyModifyHistory modifyHistory = applyModifyHistoryService.getModifyHistory(condition.getApplyNo());
        //如果存在数据留痕，就更新
        if (ObjectUtil.isNotNull(modifyHistory)) {
            modifyHistory.setApplyNo(condition.getApplyNo());
            modifyHistory.setHistoryContent(JSONObject.toJSONString(historyContent));
            modifyHistory.setBeforeParameter(JSONObject.toJSONString(assetChangeVo));
            modifyHistory.setCreateBy(SecurityUtils.getUsername());
            modifyHistory.setCreateTime(new Date());
            this.applyModifyHistoryService.updateById(modifyHistory);
        } else {
            //不存在就新增
            modifyHistory = new ApplyModifyHistory();
            modifyHistory.setApplyNo(condition.getApplyNo());
            modifyHistory.setHistoryContent(JSONObject.toJSONString(historyContent));
            modifyHistory.setBeforeParameter(JSONObject.toJSONString(assetChangeVo));
            modifyHistory.setCreateBy(SecurityUtils.getUsername());
            modifyHistory.setCreateTime(new Date());
            this.applyModifyHistoryService.save(modifyHistory);
        }
        log.info("资产变更前,数据留痕完成:{}", assetChangeVo);
        return IResponse.success(modifyHistory.getId().toString());
    }

    /**
     * 订单主表替换申请编号
     *
     * @param applyNo
     * @param tempNo
     * @return
     */
    @Override
    public int replaceOrderInfo(String applyNo, String tempNo) {

        return this.baseMapper.replaceOrderInfo(applyNo, tempNo);
    }

    /**
     * 渠道信息替换申请编号
     *
     * @param applyNo
     * @param tempNo
     * @return
     */
    @Override
    public int replaceChannelInfo(String applyNo, String tempNo) {

        return this.baseMapper.replaceChannelInfo(applyNo, tempNo);
    }

    /**
     * 车辆信息替换申请编号
     *
     * @param applyNo
     * @param tempNo
     * @return
     */
    @Override
    public int replaceCarDetails(String applyNo, String tempNo) {

        return this.baseMapper.replaceCarDetails(applyNo, tempNo);
    }

    /**
     * 挂靠信息替换申请编号
     *
     * @param applyNo
     * @param tempNo
     * @return
     */
    public int replaceAffiliatedUnit(String applyNo, String tempNo) {

        return this.baseMapper.replaceAffiliatedUnit(applyNo, tempNo);
    }

    /**
     * 附件信息替换申请编号
     *
     * @param applyNo
     * @param tempNo
     * @return
     */
    @Override
    public int replaceAttachementFile(String applyNo, String tempNo) {

        return this.baseMapper.replaceAttachementFile(applyNo, tempNo);
    }

    /**
     * 融资信息替换申请编号
     *
     * @param applyNo
     * @param tempNo
     * @return
     */
    @Override
    public int replaceCostDetails(String applyNo, String tempNo) {

        return this.baseMapper.replaceCostDetails(applyNo, tempNo);
    }

    /**
     * 贴息信息替换申请编号
     *
     * @param applyNo
     * @param tempNo
     * @return
     */
    @Override
    public int replaceDiscountDetails(String applyNo, String tempNo) {

        return this.baseMapper.replaceDiscountDetails(applyNo, tempNo);
    }

    /**
     * 融资项目替换申请编号
     *
     * @param applyNo
     * @param tempNo
     * @return
     */
    @Override
    public int replaceFinancingItems(String applyNo, String tempNo) {

        return this.baseMapper.replaceFinancingItems(applyNo, tempNo);
    }

    /**
     * 租金调整替换申请编号
     *
     * @param applyNo
     * @param tempNo
     * @return
     */
    @Override
    public int replaceRentAdjustDetails(String applyNo, String tempNo) {

        return this.baseMapper.replaceRentAdjustDetails(applyNo, tempNo);
    }

    /**
     * 客户基本信息替换申请编号
     *
     * @param applyNo
     * @param tempNo
     * @return
     */
    @Override
    public int replaceaCustBaseInfo(String applyNo, String tempNo) {

        return this.baseMapper.replaceaCustBaseInfo(applyNo, tempNo);
    }

    /**
     * 客户详细信息替换申请编号
     *
     * @param applyNo
     * @param tempNo
     * @return
     */
    @Override
    public int replaceCustPersonalDetail(String applyNo, String tempNo) {

        return this.baseMapper.replaceCustPersonalDetail(applyNo, tempNo);
    }

    /**
     * 客户联系人信息替换申请编号
     *
     * @param applyNo
     * @param tempNo
     * @return
     */
    @Override
    public int replaceCustContacts(String applyNo, String tempNo) {

        return this.baseMapper.replaceCustContacts(applyNo, tempNo);
    }

    /**
     * 客户联系地址信息替换申请编号
     *
     * @param applyNo
     * @param tempNo
     * @return
     */
    @Override
    public int replaceCustAddressDetails(String applyNo, String tempNo) {

        return this.baseMapper.replaceCustAddressDetails(applyNo, tempNo);
    }

    /**
     * 签约关系表替换申请编号
     *
     * @param applyNo
     * @param tempNo
     * @return
     */
    public int replaceSignRelation(String applyNo, String tempNo) {

        return this.baseMapper.replaceSignRelation(applyNo, tempNo);
    }

    /**
     * 签约历史表信息替换申请编号
     *
     * @param applyNo
     * @param tempNo
     * @return
     */
    public int replaceSignHistory(String applyNo, String tempNo) {

        return this.baseMapper.replaceSignHistory(applyNo, tempNo);
    }

    /**
     * 替换临时编号的12表数据
     *
     * @param tempNo
     * @return
     */
    @Override
    public String getFormalApplyNo(String tempNo, String businessType, String certNo) {

        // 获取申请编号
        String applyNo = preApproveService.getPreApproveInfoApplyNO(businessType, certNo);
        if (StringUtil.isEmpty(applyNo)) {
            applyNo = applySequenceService.getApplyNo(businessType);
        }
        // 当存在历史数据时，重新生成一个新申请编号
        ApplyOrderInfo orderInfo = orderInfoService.getOrderInfoByApplyNo(applyNo);
        if (orderInfo != null) {
            applyNo = applySequenceService.getApplyNo(businessType);
        }
        // 覆盖申请编号
        this.replaceOrderInfo(applyNo, tempNo);
        this.replaceChannelInfo(applyNo, tempNo);
        this.replaceCarDetails(applyNo, tempNo);
        this.replaceAffiliatedUnit(applyNo, tempNo);
        this.replaceAttachementFile(applyNo, tempNo);
        this.replaceCostDetails(applyNo, tempNo);
        this.replaceFinancingItems(applyNo, tempNo);
        this.replaceDiscountDetails(applyNo, tempNo);
        this.replaceRentAdjustDetails(applyNo, tempNo);
        this.replaceaCustBaseInfo(applyNo, tempNo);
        this.replaceCustPersonalDetail(applyNo, tempNo);
        this.replaceCustContacts(applyNo, tempNo);
        this.replaceCustAddressDetails(applyNo, tempNo);
        this.replaceSignRelation(applyNo, tempNo);
        this.replaceSignHistory(applyNo, tempNo);

        return applyNo;
    }

    /**
     * 申请进件-更新重出标识
     *
     * @param applyNo
     */
    @Override
    public void updateReappearFlag(String applyNo) {

        // 订单信息
        ApplyOrderInfo applyOrderInfo = orderInfoService.getOrderInfoByApplyNo(applyNo);
        if (applyOrderInfo != null) {
            applyOrderInfo.setReappearFlag(WhetherEnum.No.getIndex());
            orderInfoService.updateById(applyOrderInfo);
        }
        // 客户信息
        List<ApplyCustBaseInfo> custList = custBaseInfoService.getCustBaseInfoList(applyNo);
        if (custList != null && custList.size() > 0) {
            for (ApplyCustBaseInfo applyCustBaseInfo : custList) {
                applyCustBaseInfo.setReappearFlag(WhetherEnum.No.getIndex());
                custBaseInfoService.updateById(applyCustBaseInfo);
            }
        }

    }
}
